import os
import sys
sys.path.append(os.getcwd())
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
import time
from impl.importWallet_linea import WalletUtil



# 测试网页实例
class linea_auto_nft2me:

    password = None
    MetamaskTitle = 'MetaMask'
    driverExt = None
    flag = None

    def __init__(self, driverExt, flag, password,display) -> None:
        self.driverExt = driverExt
        self.flag = flag
        self.password = password
        self.display = display
   # 主方法判断是否存在配置文件 以及创建初始自动化环境变量

    def auto_nft2me(self):
        self.display.displayInfo('运行示例中')
        windows = self.driverExt.window_handles
        wait = WebDriverWait(self.driverExt, 10)
        Nft2title = None
        # 存在配置文件即已经登录过
        if (self.flag == 1):
            self.reLoginMetaMask(self.driverExt, wait, windows)
        
            # nft2me 任务
            self.driverExt.get('https://nfts2me.com/app')
            Nft2title = self.driverExt.title
            try:
                # 如果登录状态存在直接开始创建
                address = wait.until(EC.presence_of_element_located(
                    (By.XPATH, '//*[@id="wallet"]/div[2]/button[2]/div[2]/div/div[2]/div'))).text
                if (address is not None):
                    self.nft2me_createNft(
                        self.driverExt, wait, Nft2title, None)
            except Exception as e:
                # os.system('puase')
                # display.displayInfo('钱包' + str(count) + ' 自动交互失败')
                print(e)

            self.nft2me_sign(self.driverExt, wait, Nft2title, None)
            #self.nft2me_createNft(self.driverExt, wait, Nft2title, None)
        else:
            
            # nft2me 任务
            self.driverExt.get('https://nfts2me.com/app')
            Nft2title = self.driverExt.title

            self.nft2me_connectWallet(
                self.driverExt, wait, Nft2title, None)
            self.nft2me_sign(self.driverExt, wait, Nft2title, 1)
            self.driverExt.quit()
           # self.nft2me_createNft(self.driverExt, wait, Nft2title, 1)

    def reLoginMetaMask(self, driverExt, wait, windows):
        try:
            driverExt.get(
                'chrome-extension://nkbihfbeogaeaoehlefnkodbefgpgknn/home.html#unlock')
            driverExt.switch_to.window(windows[0])

            wait.until(EC.element_to_be_clickable((
                By.XPATH, '//*[@id="password"]'))).send_keys(str(self.password))
            time.sleep(1)
            driverExt.find_element(
                By.XPATH, '//*[@id="app-content"]/div/div[3]/div/div/button').click()
        except Exception as e:
            print(e)
            print('重新登录遇到问题(可能是RPC问题)或者钱包导入失败')
            # os.system('pause')
            try:
                MetamaskError = wait.until(EC.presence_of_element_located(
                    (By.XPATH, '//*[@id="critical-error-button"]')))
                if (MetamaskError is not None):
                    driverExt.refresh()
                    self.reLoginMetaMask(driverExt, wait, windows)

            except:
                time.sleep(10)
                try:
                    #切换网络逻辑
                    switchNet = wait.until(EC.presence_of_element_located((
                        By.XPATH, '//*[@id="app-content"]/div/div[3]/div[1]/div[2]/div/div/button[1]')))
                    if (switchNet is not None):
                        switchNet.click()
                        driverExt.find_element(
                            By.XPATH, '//*[@id="app-content"]/div/div[2]/div/div[2]/li[1]/span').click()
                    self.reLoginMetaMask(driverExt, wait, windows)
                except:
                    pass

                # driverExt.refresh()
                # self.reLoginMetaMask(self, driverExt, wait, windows)
            # os.system('pause')

    def nft2me_connectWallet(self, driverExt, wait, title, flag):
        try:
            if ('请稍后...' in driverExt.title):
                wait.until(EC.element_to_be_clickable((
                    By.XPATH, '//*[@id="challenge-stage"]/div/label/input'))).click()
            # 新登录状态直接跳转签名
            if (flag is None):
                wait.until(EC.element_to_be_clickable((
                    By.XPATH, '//*[@id="wallet"]/div/button'))).click()

            driverExt.find_element(
                By.XPATH, '/html/body/div[2]/div/div/div[2]/div/div/div/div/div/div[2]/div[2]/div/button/div').click()

            # 切换metamask
            driverExt.implicitly_wait(3)
            self.switch_windows_with_title(self.MetamaskTitle, driverExt)

            # 刷新
            driverExt.refresh()
            driverExt.implicitly_wait(5)
            # 确认链接钱包
            wait.until(EC.element_to_be_clickable((
                By.XPATH, '//*[@id="app-content"]/div/div[2]/div/div[3]/div[2]/button[2]'))).click()
            wait.until(EC.element_to_be_clickable((
                By.XPATH, '//*[@id="app-content"]/div/div[2]/div/div[2]/div[2]/div[2]/footer/button[2]'))).click()
            try:
                testnetDisplay = driverExt.find_element(
                    By.XPATH, '//*[@id="app-content"]/div/div[2]/div/div[1]/div[3]/span/a')
                if (testnetDisplay is not None):
                    testnetDisplay.click()
                    driverExt.find_element(
                        By.XPATH, '//*[@id="app-content"]/div/div[3]/div/div[2]/div[2]/div[2]/div[5]/div[2]/div/label/div[1]/div[2]').click()
                    # driverExt.get(
                    #     'chrome-extension://nkbihfbeogaeaoehlefnkodbefgpgknn/home.htm')
            except:
                pass
            # 切换回网站
            self.switch_windows_with_title(title, driverExt)
            time.sleep(2)
        except:
            raise Exception('wrong page or network slow')

    def nft2me_sign(self, driverExt, wait, title, flag):

        if ('请稍后...' in driverExt.title):
            wait.until(EC.element_to_be_clickable((
                By.XPATH, '//*[@id="challenge-stage"]/div/label/input'))).click()

        # 签名
        # 新用户文件第一次登录签名不需要点击connect
        if (flag is None):
            wait.until(EC.element_to_be_clickable((
                By.XPATH, '//*[@id="wallet"]/div/button'))).click()
        # 可能要重新登录转到登录方法
        try:
            connect = driverExt.find_element(
                By.XPATH, '/html/body/div[2]/div/div/div[2]/div/div/div/div/div[1]/div[2]/div[2]/div/button/div/div/div[2]/div[1]')

            if (connect is not None):
                self.nft2me_connectWallet(driverExt, wait, title, 1)
        except:
            pass
        time.sleep(3)

        if (flag is None):
            wait.until(EC.element_to_be_clickable((
                By.XPATH, '/html/body/div[3]/div/div/div[2]/div/div/div/div/div[2]/div[2]/button[1]/div'))).click()
        elif (flag == 2):
            wait.until(EC.element_to_be_clickable((
                By.XPATH, '/html/body/div[7]/div/div/div[2]/div/div/div/div/div[2]/div[2]/button[1]/div'))).click()
            # os.system('pause')
        else:
            driverExt.find_element(
                By.XPATH, '/html/body/div[2]/div/div/div[2]/div/div/div/div/div[2]/div[2]/button[1]/div').click()
            driverExt.find_element(
                By.XPATH, '/html/body/div[2]/div/div/div[2]/div/div/div/div/div[2]/div[2]/button[1]/div').click()

        time.sleep(2)

        # 切换到小狐狸确认签名

        self.switch_windows_with_title(self.MetamaskTitle, driverExt)
        driverExt.refresh()
        driverExt.implicitly_wait(3)
        # os.system('pause')
        wait.until(EC.element_to_be_clickable((
            By.XPATH, '//*[@id="app-content"]/div/div[3]/div/div[3]/footer/button[2]'))).click()
        # 切换回网页
        self.switch_windows_with_title(title, driverExt)

        # driverExt.switch_to.window(windows[0])

    def nft2me_createNft(self, driverExt, wait, title, flag):
        # create NFT
        driverExt.get('https://nfts2me.com/create/edition/')
        createTitle = driverExt.title
        driverExt.implicitly_wait(3)

        # 可能需要重新登录
        try:
            reconnect = driverExt.find_element(
                By.XPATH, '//*[@id="wallet"]/div[2]/button')
            # os.system('pause')
            if (reconnect is not None):
                reconnect.click()
                self.nft2me_sign(driverExt, wait, title, 2)
                time.sleep(1)
                self.switch_windows_with_title(createTitle, driverExt)
        except Exception as e:
            print(e)
            pass
        time.sleep(2)
        # 切换网络
        wait.until(EC.element_to_be_clickable((
            By.XPATH, '//*[@id="__next"]/div/div/div[1]/div[2]/div/div/form/div/div[1]/div/div[1]/div[2]/div/div/button/div[2]'))).click()
        wait.until(EC.element_to_be_clickable((
            By.XPATH, '/html/body/div[4]/div/div/div[2]/div[2]/div[2]/div'))).click()

        wait.until(EC.element_to_be_clickable((
            By.XPATH, '/html/body/div[4]/div/div/div[2]/div[3]/div/div[4]/div/div/div/div/div[2]'))) .click()
        time.sleep(3)
        # 获取RPC连接状态
        status = wait.until(EC.presence_of_element_located((
            By.XPATH, '/html/body/div[4]/div/div/div[2]/div[3]/div/div[4]/div/div/div/div[2]/div[1]'))).text
       # 切换到metamask确认
        self.switch_windows_with_title(self.MetamaskTitle, driverExt)
        driverExt.refresh()
        driverExt.implicitly_wait(3)

        # 新用户文件需要新添加网络
        if (flag is not None):
            wait.until(EC.element_to_be_clickable(
                (By.XPATH, '//*[@id="app-content"]/div/div[2]/div/div[2]/div/button[2]'))).click()

        # 判断是否以及链接RPC
        if ('Connected' not in status):
            wait.until(EC.element_to_be_clickable(
                (By.XPATH, '//*[@id="app-content"]/div/div[2]/div/div[2]/div/button[2]'))).click()
            time.sleep(1)

        self.switch_windows_with_title(createTitle, driverExt)
        driverExt.refresh()
        driverExt.implicitly_wait(3)
        os.system('pause') 
        # 输入fee值并开始部署
        input = driverExt.find_element(
            By.XPATH, '//*[@id="__next"]/div/div/div[1]/div[2]/div/div/form/div[1]/div[1]/div[2]/div/div[1]/div/div/input')
        input.clear()
        input.send_keys('0.01')
        os.system('pause')
        wait.until(EC.element_to_be_clickable((
            By.XPATH, '//*[@id="__next"]/div/div/div[1]/div[2]/div/div/form/div[2]/div/button'))).click()

    def switch_windows_with_title(self, target_title, driverExt):
        # 遍历windows_handle寻找对应的窗口
        for handle in driverExt.window_handles:
            driverExt.switch_to.window(handle)
            if target_title in driverExt.title:
                break

    def test_auto(self):
        EXTENSION_PATH = os.path.join(os.getcwd(), "lib", "metamask.crx")

        word = 'lemon attack general push agent loud color civil evil solution okay inmate'
        EXTENSION_ID = 'nkbihfbeogaeaoehlefnkodbefgpgknn'
        executablePath = os.path.join(os.getcwd(), "lib", "chromedriver.exe")
        password = 'm,./1234'
        # 输入环境参数得到driver
        wallet = WalletUtil(EXTENSION_PATH, word,
                            EXTENSION_ID, executablePath, password)
        driverExt, flag = wallet.importSingleWallet()

        # 创建自动化逻辑对象
        auto_nft2me = linea_auto_nft2me(
            driverExt, flag, password)
        auto_nft2me.auto_nft2me()

        os.system('pause')

    def readWord():
        filename = os.getcwd() + "/lib/config.txt"
        word_list = []
        # 逐行读取文件并将助记词存储到数组中
        with open(filename, 'r', encoding='utf-8') as file:
            for line in file:
                line = line.strip()  # 去除行首行尾的空白字符
                if not line.startswith('#'):

                    word_list.append(line)
        return word_list


if __name__ == "__main__":

    # print(os.path.exists(str(linea_auto.EXTENSION_PATH)))
    # linea_auto.chrom_auto_nft2me(linea_auto)
    # linea_auto.test_auto(linea_auto)
    linea_auto_nft2me.test_auto(linea_auto_nft2me)
